// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  //这个是获取所有的项目列表（用于给志愿者报名用）
  if (event.flag == "project") {
    return await cloud.database().collection("project").orderBy('pubTimeStamp', event.order)
      .skip(event.len).limit(event.pageNum).where({
        taskType: cloud.database().command.in(event.conditionWhere)
      })
      .get()
  }

  //获取所有的团队（用来给志愿者报名用）
  else if (event.flag == "team") {
    return await cloud.database().collection("all_team")
      .skip(event.len).limit(event.pageNum)
      .get()
  }

  //获取该团队已截止的项目们
  else if (event.flag == "endProject") {
    return await cloud.database().collection("project")
      .where({
        endDateStamp: cloud.database().command.lt(event.nowStamp),
        teamOpenid: event.managerOpenid
      })
      .get()
  }

  //获取该团队未截止的项目们
  else if (event.flag == "ingProject") {
    return await cloud.database().collection("project")
      .where({
        endDateStamp: cloud.database().command.gt(event.nowStamp),
        teamOpenid: event.managerOpenid
      })
      .get()
  } 
  //把录取的志愿者从notAdmit丢进hasAdmit
  else if (event.flag == "act_admit") {
    return await cloud.database().collection("project").doc(event.project_id)
      .update({
        data: {
          vlnListNotAdmit: cloud.database().command.pull({
            _id: event.vln_id
          }),
          vlnListHasAdmit: cloud.database().command.push({
            vln_id: event.vln_id,
            vln_openid: event.vln_openid,
            vln_name: event.vln_name,
            vln_avar: event.vln_avar,
          })
        }
      })
  } 
  //把未录取的志愿者丢掉
  else if (event.flag == "act_no_admit") {
    return await cloud.database().collection("project").doc(event.project_id)
      .update({
        data: {
          vlnListNotAdmit: cloud.database().command.pull({
            _id: event.vln_id
          })
        }
      })
  }
  else if (event.flag == "getTeamProject") {
    return await cloud.database().collection("project")
    .where({
      teamOpenid:event.teamOpenid
    }).get()
  }
  else if (event.flag == "getTextAndPic") {
    return await cloud.database().collection("textAndPic").orderBy("time","desc")
    .get()
  }
}